package net.lab1024.sa.admin.module.business.erp.prp.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.lab1024.sa.admin.module.business.erp.inv.domain.vo.TargetVo;
import net.lab1024.sa.admin.module.business.erp.prp.domain.form.BipordAddForm;
import net.lab1024.sa.admin.module.business.erp.prp.domain.form.BipordQueryForm;
import net.lab1024.sa.admin.module.business.erp.prp.domain.form.BipordUpdateForm;
import net.lab1024.sa.admin.module.business.erp.prp.domain.vo.BipordVO;
import net.lab1024.sa.admin.module.business.erp.prp.domain.vo.BipordaVO;
import net.lab1024.sa.admin.module.business.erp.mmo.dao.MmordDao;
import net.lab1024.sa.admin.module.business.erp.mmo.domain.entity.MmordEntity;
import net.lab1024.sa.admin.module.business.erp.poo.dao.PuordDao;
import net.lab1024.sa.admin.module.business.erp.poo.dao.PuordaDao;
import net.lab1024.sa.admin.module.business.erp.poo.domain.entity.PuordEntity;
import net.lab1024.sa.admin.module.business.erp.poo.domain.entity.PuordaEntity;
import net.lab1024.sa.admin.module.business.erp.prp.dao.BipordDao;
import net.lab1024.sa.admin.module.business.erp.prp.dao.BipordaDao;
import net.lab1024.sa.admin.module.business.erp.prp.dao.BipordbDao;
import net.lab1024.sa.admin.module.business.erp.prp.domain.entity.BipordEntity;
import net.lab1024.sa.admin.module.business.erp.prp.domain.entity.BipordbEntity;
import net.lab1024.sa.admin.module.business.erp.prp.domain.vo.BipordbVO;
import net.lab1024.sa.base.common.code.ErpErrorCode;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * BIP运算单 Service
 *
 * @Author AKITA
 * @Date 2025-08-13 14:18:32
 * @Copyright AKITA
 */

@Service
public class BipordService {

    @Resource
    private BipordDao bipordDao;
    @Resource
    private BipordaDao bipordaDao;
    @Resource
    private BipordbDao bipordbDao;
    @Resource
    private MmordDao mmordDao;
    @Resource
    private PuordDao puordDao;
    @Resource
    private PuordaDao puordaDao;

    public PageResult<BipordVO> queryPage(BipordQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<BipordVO> list = bipordDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    public ResponseDTO<Long> add(BipordAddForm addForm) {
        BipordEntity bipordEntity = SmartBeanUtil.copy(addForm, BipordEntity.class);
        bipordDao.insert(bipordEntity);

        return ResponseDTO.ok(bipordEntity.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(BipordUpdateForm updateForm) {
        BipordEntity bipordEntity = SmartBeanUtil.copy(updateForm, BipordEntity.class);
        bipordDao.updateById(bipordEntity);
        bipordbDao.deleteById(updateForm.getId());
        for (BipordaVO bipordaVO : updateForm.getLista()) {
            for (BipordbVO bipordbVO : bipordaVO.getLista()) {
                bipordbDao.insert(SmartBeanUtil.copy(bipordbVO, BipordbEntity.class));
            }
        }





        return ResponseDTO.ok();
    }

    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        bipordDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    @Transactional
    public ResponseDTO<String> delete(Long id) {


        List<PuordaEntity> puordaEntities = puordaDao.selectList(new LambdaQueryWrapper<PuordaEntity>().eq(PuordaEntity::getBaseId, id));

        if (!puordaEntities.isEmpty()){
            return ResponseDTO.error(ErpErrorCode.PARAM_ERROR,"存在请购单，禁止删除！");
        }

        List<MmordEntity> mmordEntities = mmordDao.selectList(new LambdaQueryWrapper<MmordEntity>().eq(MmordEntity::getBaseId, id));


        if (!mmordEntities.isEmpty()){
            return ResponseDTO.error(ErpErrorCode.PARAM_ERROR,"存在生产订单，禁止删除！");
        }


        bipordDao.deleteById(id);
        bipordaDao.deleteById(id);
        bipordbDao.deleteById(id);
        return ResponseDTO.ok();
    }

    public ResponseDTO<BipordVO> info(Long id) {
        BipordEntity bipordEntity = bipordDao.selectById(id);
        BipordVO copy = SmartBeanUtil.copy(bipordEntity, BipordVO.class);
        List<BipordaVO> voList = bipordaDao.info(id);
        copy.setLista(voList);





        ArrayList<TargetVo> targetVob = new ArrayList<>();
        for (BipordaVO puordaVO : voList) {
            if (puordaVO.getBaseId() != null) {
                TargetVo targetVo = new TargetVo();
                targetVo.setId(puordaVO.getBaseId());
                targetVo.setLineNum(puordaVO.getBaseLineNum());
                targetVo.setItemId(puordaVO.getItemId());
                targetVo.setItemName(puordaVO.getItemName());
                targetVo.setQty(puordaVO.getQty());
                targetVob.add(targetVo);
            }
        }


        copy.setListb(targetVob);






        return ResponseDTO.ok(copy);
    }



    @Transactional
    public ResponseDTO<String> passDown(Long id, Integer version) {

        List<BipordbEntity> bipordbEntities = bipordbDao.selectList(new LambdaQueryWrapper<BipordbEntity>().eq(BipordbEntity::getId, id));



        List<BipordbEntity> collecta = bipordbEntities.stream().filter(item -> item.getSource().equals("01")).collect(Collectors.toList());

        List<BipordbEntity> collectb = bipordbEntities.stream().filter(item -> item.getSource().equals("02")).collect(Collectors.toList());



        for (BipordbEntity bipordbEntity : collecta) {
            MmordEntity mmordEntity = new MmordEntity();
            mmordEntity.setItemId(bipordbEntity.getItemId());
            mmordEntity.setItemName(bipordbEntity.getItemName());
            mmordEntity.setQty(bipordbEntity.getQty());
            mmordEntity.setConnum(bipordbEntity.getConnum());
            mmordEntity.setSpecs(bipordbEntity.getSpecs());
            mmordEntity.setUnit(bipordbEntity.getUnit());
            mmordDao.insert(mmordEntity);
        }
        if (!collectb.isEmpty()){
            PuordEntity puordEntity = new PuordEntity();
            puordDao.insert(puordEntity);
            int lineNum = 1;
            for (BipordbEntity bipordbEntity : collectb) {
                PuordaEntity puordaEntity = new PuordaEntity();
                puordaEntity.setId(puordEntity.getId());
                puordaEntity.setLineNum(lineNum++);
                puordaEntity.setBaseId(bipordbEntity.getId());
                puordaEntity.setBaseLineNum(bipordbEntity.getLineNum());
                puordaEntity.setItemId(bipordbEntity.getItemId());
                puordaEntity.setItemName(bipordbEntity.getItemName());
                puordaEntity.setQty(bipordbEntity.getQty());
                puordaEntity.setSpecs(bipordbEntity.getSpecs());
                puordaEntity.setUnit(bipordbEntity.getUnit());
                puordaDao.insert(puordaEntity);

            }

        }
        if (!upDateVesrion(id,version)) throw new RuntimeException("数据异常，刷新重试！");
        return ResponseDTO.ok();
    }


    public Boolean checkVersion(Long id, Integer version) {

        return bipordDao.selectOne(new LambdaQueryWrapper<BipordEntity>().eq(BipordEntity::getId, id).eq(BipordEntity::getVersion, version)) != null;
    }

    public Boolean upDateVesrion(Long id, Integer version) {
        BipordEntity bipordEntity = bipordDao.selectOne(new LambdaQueryWrapper<BipordEntity>().eq(BipordEntity::getId, id).eq(BipordEntity::getVersion, version));
        if (bipordEntity == null) return false;
        bipordEntity.setIssuStatus(true);
        return bipordDao.updateById(bipordEntity) != 0;
    }
}
